package com.situ.user.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.situ.user.bean.Goods;
import com.situ.user.bean.Shopcart;
import com.situ.user.mapper.GoodsMapper;
import com.situ.user.mapper.ShopcartMapper;
import com.situ.user.service.ShopcartService;

@Service
public class ShopcartServiceImpl implements ShopcartService {

	@Autowired
	private ShopcartMapper shopcartMapper;

	@Autowired
	private GoodsMapper goodsMapper;

	@Override
	public int add(Shopcart cart) {
		// 1查询有没有对应的信息
		Shopcart selectShopcart = shopcartMapper.select(cart);
		if (selectShopcart != null) {
			// 先数量+1
			selectShopcart.setCount(selectShopcart.getCount() + 1);
			// 更新倒数据库
			return shopcartMapper.updateByPrimaryKey(selectShopcart);
		} else {
			// 直接插入
			return shopcartMapper.insert(cart);
		}

	}

	@Override
	@Transactional
	public List getByUserId(Integer id) {
		// 根据用户id查询用户的所有购物车
		List<Shopcart> carts = shopcartMapper.selectByUserId(id);
		// 遍历所有的购物车信息
		for (Shopcart cart : carts) {
			// 判断购物车信息是否正常
			if (cart.getCount() > cart.getGoods().getCount()) {
				// 修改购物车的数量
				cart.setCount(cart.getGoods().getCount());
				// 信息更新到数据库中
				shopcartMapper.updateByPrimaryKey(cart);
			}
		}
		return carts;

	}

	@Override
	public Shopcart update(Shopcart shopcart) {
		Shopcart selectCart = shopcartMapper.selectByPrimaryKey(shopcart.getId());

		Goods goods = goodsMapper.selectByPrimaryKey(selectCart.getGoodsId());

		if (goods.getCount() < shopcart.getCount()) {
			selectCart.setCount(goods.getCount());
			shopcartMapper.updateByPrimaryKey(selectCart);
		} else {
			shopcartMapper.updateByPrimaryKey(shopcart);
		}
		return shopcartMapper.selectByPrimaryKey(shopcart.getId());
	}

	@Override
	public Shopcart remove(Integer id) {
		Shopcart shopcart = shopcartMapper.selectByPrimaryKey(id);
		shopcartMapper.deleteByPrimaryKey(id);
		return shopcart;
	}

}
